﻿using System;
using System.Configuration;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace QLTK.User_Control
{
    public partial class XtraConfig : XtraUserControl
    {
        public XtraConfig()
        {
            InitializeComponent();
            ClearTextbox();
            ShowConfig();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            UpdateConfig(txtConnectionString.Text);
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            splashScreenManagerConfig.ShowWaitForm();
            var db = new Database();
            db.CheckConnect();
            db.CloseConnect();
            splashScreenManagerConfig.CloseWaitForm();
        }

        private void ClearTextbox()
        {
            txtConnectionString.Clear();
        }

        private void ShowConfig()
        {
            txtConnectionString.Text = ConfigurationManager.ConnectionStrings["QLTK.Properties.Settings.QLTKConnection"].ConnectionString;
            txtSLTK.Text = ConfigurationManager.AppSettings["SLTK"];
        }

        private void UpdateConfig(string connstr)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.ConnectionStrings.ConnectionStrings["QLTK.Properties.Settings.QLTKConnection"].ConnectionString = txtConnectionString.Text;
            config.AppSettings.Settings["SLTK"].Value = txtSLTK.Text;
            if (Convert.ToInt32(txtSLTK.Text) >= 200)
            {
                MessageBox.Show("Số lượng tờ khai trong hộp qua nhiều");
            }
            else
            {
                try
                {
                    config.Save(ConfigurationSaveMode.Modified, true);
                    ConfigurationManager.RefreshSection("connectionStrings");
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }

                MessageBox.Show("Thay đổi thành công", "QLTK");
            }
            
        }
    }
}